<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Post;

/**
 * PostSearch represents the model behind the search form about `common\models\Post`.
 */
class PostSearch extends Post
{
    /**
     * 2. 添加自定义字段
     * @return array
     */
    public function attributes()
    {
        return array_merge(parent::attributes(), ['authorName']);
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'status', 'create_time', 'update_time', 'author_id'], 'integer'],
            [['title', 'content', 'tags', 'authorName'], 'safe'], // 3. 增加规则
        ];
    }

    /**
     * @inheritdoc 场景设置 -- 父类设置为空
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Post::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => ['pageSize' => 10], //分页
            'sort' => [ //排序
                'defaultOrder' => ['id' => SORT_DESC],
                //'attributes' => ['id', 'title'], // 可以点击排序字段
            ],
        ]);

        $this->load($params); //加载输入的内容

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions  查询条件赋值
        $query->andFilterWhere([
            'post.id' => $this->id,
            'status' => $this->status,
            'create_time' => $this->create_time,
            'update_time' => $this->update_time,
            //'author_id' => $this->author_id,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'content', $this->content])
            ->andFilterWhere(['like', 'tags', $this->tags]);
        // 4.1增加连接查询 -- 不能用 right join 否则会出现 未设置 的提示框
        $query->join('LEFT JOIN', 'adminuser', 'post.author_id = adminuser.id');
        // 4.2增加语句查询
        $query->andFilterWhere(['like', 'adminuser.nickname', $this->authorName]);

        // 4.3 排序可用
        $dataProvider->sort->attributes['authorName'] = [
            'asc' => ['adminuser.nickname' => SORT_ASC],
            'desc' => ['adminuser.nickname' => SORT_DESC],
        ];

        return $dataProvider;
    }
}
